<?php

namespace App\Http\Controllers\Third;

use App\User;
use EasyWeChat\Foundation\Application;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;

class WechatController extends Controller
{
    protected $wechat_receipt;
    protected $wechat_payment;

    public function __construct()
    {
        $this->wechat_receipt = new Application([
            'app_id' => env('RECEIPT_WECHAT_APPID'),
            'secret' => env('RECEIPT_WECHAT_SECRET'),
            'oauth' => [
                'scopes' => ['snsapi_base'],
                'callback' => '/third/wechat/callback-receipt',
            ],
        ]);
        $this->wechat_payment = new Application([
            'app_id' => env('PAYMENT_WECHAT_APPID'),
            'secret' => env('PAYMENT_WECHAT_SECRET'),
            'oauth' => [
                'scopes' => ['snsapi_base'],
                'callback' => '/third/wechat/callback-payment',
            ],
        ]);
    }

    public function auth_receipt(Request $request)
    {
        session(['user_receipt' => $request->input('user')]);
        session(['url_receipt' => $request->input('url')]);
        return $this->wechat_receipt->oauth->redirect();
    }

    public function callback_receipt()
    {
        $oauth = $this->wechat_receipt->oauth;
        $openid = $oauth->user()->id;
        if (!User::where('openid_receipt', $openid)->exists()) {
            try {
                $user_id = Crypt::decrypt(session('user_receipt'));
                $user = User::find($user_id);
                if (!$user->openid_receipt) {
                    $user->openid_receipt = $openid;
                    $user->save();
                }
            } catch (DecryptException $e) {
            }
        }
        return redirect(session('url_receipt', 'user'));
    }

    public function auth_payment(Request $request)
    {
        session(['user_payment' => $request->input('user')]);
        session(['url_payment' => $request->input('url')]);
        return $this->wechat_payment->oauth->redirect();
    }

    public function callback_payment()
    {
        $oauth = $this->wechat_payment->oauth;
        $openid = $oauth->user()->id;
        if (!User::where('openid_payment', $openid)->exists()) {
            try {
                $user_id = Crypt::decrypt(session('user_payment'));
                $user = User::find($user_id);
                if (!$user->openid_payment) {
                    $user->openid_payment = $openid;
                    $user->save();
                }
            } catch (DecryptException $e) {
            }
        }
        return redirect(session('url_payment', 'user'));
    }
}
